<template>
  <div>
    <h2>Email Addresses</h2>
    
    <div class="action-buttons">
      <el-button type="primary" @click="showImportDialog">Import Addresses</el-button>
      <el-button type="success" @click="showAddDialog">Add Address</el-button>
    </div>
    
    <!-- Filter by Group -->
    <el-select v-model="selectedGroup" placeholder="Filter by Group" clearable @change="loadEmailAddresses">
      <el-option
        v-for="group in groups"
        :key="group"
        :label="group"
        :value="group">
      </el-option>
    </el-select>
    
    <!-- Email Addresses Table -->
    <el-table :data="emailAddresses" style="width: 100%; margin-top: 20px;" v-loading="loading">
      <el-table-column prop="id" label="ID" width="80"></el-table-column>
      <el-table-column prop="email" label="Email" width="250"></el-table-column>
      <el-table-column prop="name" label="Name" width="150"></el-table-column>
      <el-table-column prop="groupName" label="Group" width="150"></el-table-column>
      <el-table-column prop="remark" label="Remark"></el-table-column>
      <el-table-column label="Actions" width="150">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEdit(scope.row)">Edit</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.row)">Delete</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- Pagination -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      style="margin-top: 20px;">
    </el-pagination>
    
    <!-- Import Dialog -->
    <el-dialog title="Import Email Addresses" :visible.sync="importDialogVisible" width="500px">
      <el-form :model="importForm" label-width="120px">
        <el-form-item label="Group Name">
          <el-input v-model="importForm.groupName" placeholder="Enter group name"></el-input>
        </el-form-item>
        <el-form-item label="CSV File">
          <el-upload
            class="upload-demo"
            action="/api/email-addresses/import"
            :on-success="handleImportSuccess"
            :on-error="handleImportError"
            :data="{ groupName: importForm.groupName }"
            :before-upload="beforeUpload"
            :show-file-list="true">
            <el-button size="small" type="primary">Click to upload</el-button>
            <div slot="tip" class="el-upload__tip">Upload CSV file with email,name columns</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="importDialogVisible = false">Cancel</el-button>
      </span>
    </el-dialog>
    
    <!-- Add/Edit Dialog -->
    <el-dialog :title="dialogTitle" :visible.sync="formDialogVisible" width="500px">
      <el-form :model="form" :rules="rules" ref="form" label-width="120px">
        <el-form-item label="Email" prop="email">
          <el-input v-model="form.email" placeholder="Enter email address"></el-input>
        </el-form-item>
        <el-form-item label="Name" prop="name">
          <el-input v-model="form.name" placeholder="Enter name"></el-input>
        </el-form-item>
        <el-form-item label="Group" prop="groupName">
          <el-input v-model="form.groupName" placeholder="Enter group name"></el-input>
        </el-form-item>
        <el-form-item label="Remark">
          <el-input v-model="form.remark" type="textarea" placeholder="Enter remark"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="formDialogVisible = false">Cancel</el-button>
        <el-button type="primary" @click="submitForm">Confirm</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'EmailAddresses',
  data() {
    return {
      emailAddresses: [],
      loading: false,
      currentPage: 1,
      pageSize: 10,
      total: 0,
      importDialogVisible: false,
      formDialogVisible: false,
      dialogTitle: 'Add Email Address',
      isEdit: false,
      importForm: {
        groupName: ''
      },
      form: {
        id: null,
        email: '',
        name: '',
        groupName: '',
        remark: ''
      },
      rules: {
        email: [
          { required: true, message: 'Please enter email address', trigger: 'blur' },
          { type: 'email', message: 'Please enter a valid email address', trigger: 'blur' }
        ],
        groupName: [
          { required: true, message: 'Please enter group name', trigger: 'blur' }
        ]
      },
      groups: [],
      selectedGroup: ''
    };
  },
  created() {
    this.loadEmailAddresses();
    this.loadGroups();
  },
  methods: {
    loadEmailAddresses() {
      this.loading = true;
      let url = '/email-addresses';
      
      if (this.selectedGroup) {
        url = `/email-addresses/group/${this.selectedGroup}`;
        this.$axios.get(url)
          .then(response => {
            this.emailAddresses = response.data;
            this.total = response.data.length;
            this.loading = false;
          })
          .catch(error => {
            console.error('Error loading email addresses:', error);
            this.$message.error('Failed to load email addresses');
            this.loading = false;
          });
      } else {
        url += `?page=${this.currentPage}&size=${this.pageSize}`;
        this.$axios.get(url)
          .then(response => {
            this.emailAddresses = response.data.records;
            this.total = response.data.total;
            this.loading = false;
          })
          .catch(error => {
            console.error('Error loading email addresses:', error);
            this.$message.error('Failed to load email addresses');
            this.loading = false;
          });
      }
    },
    
    loadGroups() {
      this.$axios.get('/email-addresses/groups')
        .then(response => {
          this.groups = response.data;
        })
        .catch(error => {
          console.error('Error loading groups:', error);
          this.$message.error('Failed to load groups');
        });
    },
    
    handleSizeChange(size) {
      this.pageSize = size;
      this.loadEmailAddresses();
    },
    
    handleCurrentChange(page) {
      this.currentPage = page;
      this.loadEmailAddresses();
    },
    
    showImportDialog() {
      this.importDialogVisible = true;
      this.importForm.groupName = '';
    },
    
    beforeUpload(file) {
      if (!this.importForm.groupName) {
        this.$message.error('Please enter a group name');
        return false;
      }
      
      const isCsv = file.type === 'text/csv' || file.name.endsWith('.csv');
      if (!isCsv) {
        this.$message.error('Please upload CSV file');
        return false;
      }
      
      return true;
    },
    
    handleImportSuccess(response) {
      this.$message.success(`Successfully imported ${response.count} email addresses`);
      this.importDialogVisible = false;
      this.loadEmailAddresses();
      this.loadGroups();
    },
    
    handleImportError(error) {
      console.error('Import error:', error);
      this.$message.error('Failed to import email addresses');
    },
    
    showAddDialog() {
      this.dialogTitle = 'Add Email Address';
      this.isEdit = false;
      this.form = {
        id: null,
        email: '',
        name: '',
        groupName: '',
        remark: ''
      };
      this.formDialogVisible = true;
    },
    
    handleEdit(row) {
      this.dialogTitle = 'Edit Email Address';
      this.isEdit = true;
      this.form = { ...row };
      this.formDialogVisible = true;
    },
    
    handleDelete(row) {
      this.$confirm('Are you sure you want to delete this email address?', 'Warning', {
        confirmButtonText: 'Yes',
        cancelButtonText: 'No',
        type: 'warning'
      }).then(() => {
        this.$axios.delete(`/email-addresses/${row.id}`)
          .then(() => {
            this.$message.success('Email address deleted successfully');
            this.loadEmailAddresses();
          })
          .catch(error => {
            console.error('Error deleting email address:', error);
            this.$message.error('Failed to delete email address');
          });
      }).catch(() => {
        // User cancelled
      });
    },
    
    submitForm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          if (this.isEdit) {
            // Update existing email address
            this.$axios.put(`/email-addresses/${this.form.id}`, this.form)
              .then(() => {
                this.$message.success('Email address updated successfully');
                this.formDialogVisible = false;
                this.loadEmailAddresses();
              })
              .catch(error => {
                console.error('Error updating email address:', error);
                this.$message.error('Failed to update email address');
              });
          } else {
            // Add new email address
            this.$axios.post('/email-addresses', this.form)
              .then(() => {
                this.$message.success('Email address added successfully');
                this.formDialogVisible = false;
                this.loadEmailAddresses();
                this.loadGroups();
              })
              .catch(error => {
                console.error('Error adding email address:', error);
                this.$message.error('Failed to add email address');
              });
          }
        }
      });
    }
  }
}
</script>
